﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using UDFSocket;

namespace PhoneServiceTest
{
    /// <summary>
    /// 2013/1/31
    /// YGJ
    /// 查看链接的电话信息
    /// </summary>
    public partial class CPMForm : Form
    {
        public CPMForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 窗体载入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CPMForm_Load(object sender, EventArgs e)
        {

        }
        void BtnStartClick(object sender, EventArgs e)
        {
            Thread newThread = new Thread(new ThreadStart(StartListen));
            newThread.Start();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //string strMsg = File.ReadAllText(@"C:\Users\Administrator\Desktop\PhoneRec.txt");
            //byte[] bytes = Convert.FromBase64String(strMsg);
            //var length = Encoding.Default.GetString(bytes, 0, 4);
            //var func = Encoding.Default.GetString(bytes, 4, 2);
            //var seq_no = Encoding.Default.GetString(bytes, 6, 4);
            //var id = Encoding.Default.GetString(bytes, 10, 18);


            var bytes = PublicMethod.ReadBytesFormFile(@"D:\data\11115.txt");
            var length = Encoding.Default.GetString(bytes, 0, 4);
            var func = Encoding.Default.GetString(bytes, 4, 2);
            var seq_no = Encoding.Default.GetString(bytes, 6, 4);
            var id = Encoding.Default.GetString(bytes, 10, 18);
            var version = Encoding.Default.GetString(bytes, 28, 18);
            var moniter = Encoding.Default.GetString(bytes, 46, 72);
        }
        /// <summary>
        /// 开始监听某个端口
        /// </summary>
        private void StartListen()
        {
            TcpListener listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), 12122);//PublicConstValue.LOCALHOST, 12122);
            listener.Start(); // 开始监听
            TcpClient remotClient = null;
            try
            {
                while (true)
                {
                    #region

                    //TcpListener listener = new TcpListener(PublicConstValue.LOCALHOST, 12122);
                    //listener.Start();
                    ////建立连接
                    //TcpClient remotClient = listener.AcceptTcpClient();
                    //byte[] buffer = new byte[PublicConstValue.BUFFERSIZE];
                    //NetworkStream streamFromClicent = remotClient.GetStream();
                    ////读取数据
                    //int byteRead = streamFromClicent.Read(buffer, 0, PublicConstValue.BUFFERSIZE);
                    ////根据协议解析数据
                    //Message msg = new Message();
                    //msg.IsRequest = true;
                    //msg.FromBytes(buffer);
                    //var body = msg.Body as PHONE_AUTHEN_Request;

                    //this.txtMSG.Text += body.DeviceId;
                    ////写入数据
                    //PHONE_AUTHEN_Response responseBody = new PHONE_AUTHEN_Response();
                    //responseBody.valid_flag = "1";
                    //msg.Body = responseBody;
                    //var bytes = msg.GetBytes();
                    //streamFromClicent.Write(bytes, 0, bytes.Length);

                    #endregion

                    //建立连接
                    remotClient = listener.AcceptTcpClient(); //运行到此等待，
                    Thread newThread = new Thread(new ParameterizedThreadStart(DoWork));
                    newThread.Start(remotClient);
                }
            }
            catch (Exception ex) { }
        }
        /// <summary>
        /// 从链接中读写数据，并处理相应逻辑
        /// </summary>
        /// <param name="client"></param>
        private void DoWork(object client)
        {
            TcpClient curClient = client as TcpClient;
            try
            {
                if (curClient != null)
                {
                    byte[] buffer = new byte[1024];
                    NetworkStream netStream = curClient.GetStream();
                    Message msg = new Message();

                    netStream.Read(buffer, 0, buffer.Length);
                    msg.IsRequest = true;
                    msg.FromBytes(buffer);
                    if (msg.func_no == "10") //话机验证
                    {
                        var body = msg.Body as PHONE_AUTHEN_Request;

                        //this.txtMSG.Text += body.DeviceId;
                        //写入数据
                        PHONE_AUTHEN_Response responseBody = new PHONE_AUTHEN_Response();
                        responseBody.valid_flag = "1";
                        msg.Body = responseBody;
                        var bytes = msg.GetBytes();
                        netStream.Write(bytes, 0, bytes.Length);
                    }
                    //else if()
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 开始异步监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAnsycStart_Click(object sender, EventArgs e)
        {
            //IPEndPoint localEndPoint = new IPEndPoint(PublicConstValue.LISENEDEND_IPADDRESS, PublicConstValue.LISENEDEND_PORT);
            IPEndPoint localEndPoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 12122);

            SocketPlus server = new SocketPlus(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(localEndPoint);
            server.Listen(1000);
            server.AsyncAccept();
            server.OnThreadTaskRequest += new SocketPlus.ThreadTaskRequest(GetMsg);
        }

        private void GetMsg(object sender, EventArgs e)
        {
            SocketPlus client = (SocketPlus)sender;

            while (true)
            {
                try
                {
                    byte[] bytes = new byte[1024];
                    client.Read(out bytes);
                    Message msg = new Message();
                    msg.FromBytes(bytes);
                    if (msg.func_no == "10")
                    {
                        PHONE_AUTHEN_Response body = new PHONE_AUTHEN_Response();
                        body.valid_flag = "1";
                        msg.Body = body;

                    }
                    else if (msg.func_no == "82")
                    {
                        ABT_STATUS_Request body = new ABT_STATUS_Request();
                        msg.Body = body;
                    }
                    else if (msg.func_no == "05")
                    {
                        CONNECT_STATUS_Response body = new CONNECT_STATUS_Response();
                        msg.Body = body;
                    }
                    bytes = msg.GetBytes();
                    client.Write(bytes, 0, bytes.Length);
                }

                catch (Exception ex)
                {
                    Type type = ex.GetType();
                    if (type == typeof(TimeoutException))
                    {   // 超时异常，不中断连接

                    }
                    else
                    {   // 仍旧抛出异常，中断连接

                    }
                }
            }

        }

    }


}
